<template>
    <div class="login-contariner">
        <div class="login-way-box">
            <span class="login-tips-text">登录界面</span>
            <el-link :underline="false" class="login-type" @click="toAccountLogin">账户登录</el-link>
            .
            <el-link :underline="false" class="login-type" @click="getLoginQrImagePath">扫码登录</el-link>
        </div>

        <el-row :gutter="20" v-show="loginType">
            <el-col :span="8">
                <el-form label-position="right" label-width="80px" :model="sobUser" :rules="rules" :ref="loginForm">
                    <el-form-item label="名字" :required="true" prop="userName">
                        <el-input v-model="sobUser.userName" placeholder="输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" :required="true" prop="password">
                        <el-input v-model="sobUser.password" placeholder="输入密码" show-password></el-input>
                    </el-form-item>
                    <el-form-item label="验证码" :required="true" prop="captcha">
                        <el-input v-model="sobUser.captcha" placeholder="输入验证码"
                                  @keyup.enter.native="doLogin"></el-input>

                        <img :src="captchaPath" alt="获取验证码失败"
                             @click="updateVerifyCode"
                             class="captcha-code-cursor">
                    </el-form-item>
                    <el-form-item>
                        <el-button size="medium" type="primary" @click="doLogin">登录</el-button>
                        <el-link class="forget-tips-text" href="/forget">忘记密码?</el-link>
                    </el-form-item>
                </el-form>

            </el-col>
        </el-row>


        <div class="login-by-scan-box" v-show="!loginType">
            <div class="login-qr-code">
                <el-image ref="loginQrCode" :src="qrCodeLoginImagePath" @error="onQrCodeLoadError"></el-image>
            </div>

            <div class="login-qr-code-refresh" style="display: none">
                <span @click="getLoginQrImagePath">
                    <i class="el-icon-refresh">点击刷新二维码</i>
                </span>
            </div>

            <div class="login-scan-tips">
                请打开客户端app进行扫码登录
            </div>
        </div>
    </div>
</template>

<script>

import {hex_md5} from "assets/utils/md5";
import {checkCaptchaCode, checkUserNameUnique, doLogin, getLoginQrImagePath} from "assets/api/userApi";
import {success_code} from "assets/utils/LRConstant";
import {checkScanLoginState} from "assets/api/app-api";

export default {
    name: "index.vue",

    data() {
        return {
            // 登录的验证码信息
            loginForm: 'loginForm',
            captchaPath: '',
            loginType: true,
            qrCodeLoginKey: '',
            qrCodeLoginImagePath: '',
            isScanStateChecking: false,
            sobUser: {
                userName: '',
                password: '',
                captcha: '',
            },
            rules: {
                userName: [
                    {required: true, message: '用户名不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkUserName, trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '密码不能为空', trigger: ['change', 'blur']},
                    {validator: this.validatePass, trigger: 'blur'}
                ],
                captcha: [
                    {required: true, message: '验证码不能为空', trigger: ['change', 'blur']},
                    {validator: this.checkCaptchaCode, trigger: 'blur'}
                ]
            }
        };
    },
    methods: {
        // 点击登录的方法
        checkCaptchaCode(rule, value, callback) {
            checkCaptchaCode(value).then((result) => {
                if (result.code === success_code) {
                    callback();
                } else {
                    callback(new Error("验证码不正确"));
                }
            })
        },
        validatePass(rule, value, callback) {
            if (value === '') {
                callback(new Error('请输入密码'));
            }

            var patrn = /^[0-9]{1,20}$/;
            if (patrn.test(value)) {
                callback(new Error('不能纯数字'));
            }

            if (value.length < 6) {
                callback(new Error('密码不能少于6位'));
            }
            callback();
        },
        checkUserName(rule, value, callback) {
            if (value === '') {
                callback(new Error('用户名不能为空'));
            }
            callback();
        },
        doLogin() {
            // check env
            this.$refs[this.loginForm].validate((valid) => {

                console.log(valid);
                if (valid) {
                    // change net state
                    let user = {
                        password: hex_md5(this.sobUser.password),
                        userName: this.sobUser.userName
                    }
                    doLogin(this.sobUser.captcha, user).then((result) => {
                        // check data
                        // success state: role_guest go the portal page, role_admin go the manage page
                        // defeat state: show the server's message
                        if (result.code === success_code) {

                            this.$message.success("登录成功");
                            //  需要管理员判断
                            // 从url中获取到redirect
                            let redirect = this.$route.query.redirect;

                            if (redirect) {
                                location.href = redirect;
                            } else {
                                // 如果没有就到首页
                                this.$router.push('/');
                            }
                        } else {
                            this.updateVerifyCode();
                            this.$message.error("登录失败 cause by:" + result.message);
                        }
                    });
                } else {
                    this.$message.warning("校验未通过");
                }
            });
        },
        // 点击切换验证码
        updateVerifyCode: function () {
            // 为节约资源 一直使用一个时间戳
            // 只有单人系统才能这么做
            // 但是会导致url 一直一样， vue 不会修改界面
            // 所以添加了一个随机参数 来改变url
            this.captchaPath = "/user/captcha?random=" + Date.parse(new Date());
        },
        getLoginQrImagePath() {
            this.loginType = false;

            getLoginQrImagePath().then((result) => {
                if (result.code === success_code) {
                    this.qrCodeLoginKey = result.data.code;
                    this.qrCodeLoginImagePath = result.data.url;

                    // change ui
                    let loginQrCode = document.getElementsByClassName('login-qr-code');

                    if (loginQrCode) {
                        loginQrCode[0].style.display = 'block';

                        // 加载新的二维码
                        // 第一种方法， 调用element ui el-image 空间封装的重新加载的方法
                        // 第二种: 改变一下 url 让其自己加载
                        // this.$refs.loginQrCode.loadImage();

                        this.checkLoginState();
                    }

                    let qrCodeRefreshBox = document.getElementsByClassName('login-qr-code-refresh');

                    if (qrCodeRefreshBox) {
                        qrCodeRefreshBox[0].style.display = 'none';
                    }
                } else {
                    this.$message.error(result.message);
                }
            });
        },
        onQrCodeLoadError() {
            // change data
            this.qrCodeLoginKey = '';
            this.qrCodeLoginImagePath = '';

            // change ui
            let loginQrCode = document.getElementsByClassName('login-qr-code');

            if (loginQrCode) {
                loginQrCode[0].style.display = 'none';
            }

            let qrCodeRefreshBox = document.getElementsByClassName('login-qr-code-refresh');

            if (qrCodeRefreshBox) {
                qrCodeRefreshBox[0].style.display = 'block';
            }
        },
        checkLoginState() {
            // check data
            if (this.isScanStateChecking == true || this.loginType == true) {
                return;
            }

            if (this.qrCodeLoginKey === "") {
                this.getLoginQrImagePath();
            } else {
                // change data
                this.isScanStateChecking = true;
                console.log(this.qrCodeLoginKey);
                // submit data
                checkScanLoginState(this.qrCodeLoginKey).then((result) => {
                    // 2000 操作成功
                    // 4045 二维码过期
                    // 4046 等待扫描

                    // change data
                    console.log(result.message);

                    this.$message.success(result.message);
                    this.isScanStateChecking = false;

                    switch (result.code) {
                        case success_code:
                            // change ui (切换页面)
                            // 从url中获取到redirect
                            let redirect = this.$route.query.redirect;

                            if (redirect) {
                                location.href = redirect;
                            } else {
                                // 如果没有就到首页
                                this.$router.push('/');
                            }
                            break;
                        case 4045:
                            // change ui (二维码过期)
                            this.onQrCodeLoadError();
                            break;
                        case  4046:
                            this.checkLoginState();
                            break;
                    }
                });
            }
        },
        // 切换到账号登录
        toAccountLogin() {
            // change data
            this.qrCodeLoginKey = '';
            this.qrCodeLoginImagePath = '';

            this.isScanStateChecking = false;
            this.loginType = true;
        }
    },
    mounted: function () {
        // init data
        this.updateVerifyCode()
    }
}
</script>

<style scoped>
.admin-login-header-box {
    width: 100%;
    height: 46px;
    background-color: dodgerblue;
}

.admin-login-header-center {
    line-height: 46px;
}

.admin-login-logo {
    color: #ffffff;
    font-weight: 600;
    font-size: 20px;
}

.captcha-code-cursor {
    cursor: pointer;
    width: 80px;
    height: 38px;
    vertical-align: center;
    margin-left: 10px;
}


.login-contariner {
    margin-top: 10px;
    margin-bottom: 50px;
    padding: 10px;
    background-color: white;
    box-shadow: 0 1px 10px #afafaf;
    border-radius: 4px;
}

.forget-tips-text {
    margin-left: 10px;
}

.login-tips-text {
    font-weight: 500;
    font-size: 20px;
}

.login-way-box {
    margin-bottom: 30px;
    padding: 10px;
}

.login-type {
    color: grey;
}

.login-qr-code-refresh span {
    line-height: 235px;
    width: 235px;
    background-color: white;
    display: inline-block;
    text-align: center;
    border: solid 1px darkblue;
    cursor: pointer;
}

.login-qr-code {

}
</style>